import axios from 'axios'
import { useUserStore } from '@/stores/user'
import { useRouter } from 'vue-router'

const router = useRouter()

const axiosInstance = axios.create({
  baseURL: '/api',
  timeout: 5000,
})

// 请求拦截器
axiosInstance.interceptors.request.use(
  (config) => {
    const userStore = useUserStore()
    const userInfo = userStore.getUserInfo()

    // 检查是否过期
    if (userInfo.expiration && userInfo.expiration < Date.now()) {
      userStore.clearUserInfo()
      router.push('/login')
      return Promise.reject('用户会话已过期')
    }

    // 设置认证头
    if (userInfo.jwt) {
      config.headers.Authorization = `Bearer ${userInfo.jwt}`
    }

    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)

// 响应拦截器
axiosInstance.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    const userStore = useUserStore()
    if (error.response?.status === 401) {
      userStore.clearUserInfo()
      router.push('/login')
    }
    return Promise.reject(error)
  },
)

export default axiosInstance
